// pages/Dashboard/QuickActionsPanel.jsx
import React, { useState } from 'react';
import { useAuth } from 'contexts/AuthContext';
import { useMutation, useQuery, useQueryClient } from 'react-query';
import { 
  RemoveCreditCard, 
  SetDefaultCreditCard, 
  CancelSubscription,
  CreateCustomerPortalSession,
  Clear,
  Logout
} from 'api/mutations';
import { CustomerCards, Customer } from 'api/queries';
import {
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Paper,
  Typography,
  Menu,
  MenuItem,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Select,
  FormControl,
  InputLabel,
  CircularProgress,
  Alert
} from '@mui/material';
import {
  CreditCardOff as RemoveCardIcon,
  Star as DefaultCardIcon,
  Cancel as CancelIcon,
  OpenInNew as PortalIcon,
  ExitToApp as LogoutIcon,
  Clear as ClearIcon
} from '@mui/icons-material';

const QuickActionsPanel = ({ 
  user, 
  borderRadius = 1, 
  border = 1, 
  borderColor = 'primary.main', 
  planType = 'basic', 
  role = 'user' 
}) => {
  const { refetch } = useAuth();
  const queryClient = useQueryClient();
  const [anchorEl, setAnchorEl] = useState(null);
  const [menuType, setMenuType] = useState('');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState('');
  const [selectedValue, setSelectedValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [resultMessage, setResultMessage] = useState('');
  const [showResult, setShowResult] = useState(false);
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [selectedCardId, setSelectedCardId] = useState('');
  
  // Queries
  const { data: cardsData } = useQuery(["CustomerCards", user.accountId], CustomerCards);
  const { data: customerData } = useQuery(["Customer", user.accountId], Customer);
  
  // Mutations
  const removeCardMutation = useMutation(RemoveCreditCard, {
    onSuccess: () => {
      queryClient.invalidateQueries(["CustomerCards", user.accountId]);
      setResultMessage('Payment method removed successfully!');
      setShowResult(true);
      setIsLoading(false);
    },
    onError: (error) => {
      setResultMessage('Failed to remove payment method: ' + (error.message || 'Unknown error'));
      setShowResult(true);
      setIsLoading(false);
    }
  });
  
  const setDefaultCardMutation = useMutation(SetDefaultCreditCard, {
    onSuccess: () => {
      queryClient.invalidateQueries(["Customer", user.accountId]);
      setResultMessage('Default payment method updated successfully!');
      setShowResult(true);
      setIsLoading(false);
    },
    onError: (error) => {
      setResultMessage('Failed to update default payment method: ' + (error.message || 'Unknown error'));
      setShowResult(true);
      setIsLoading(false);
    }
  });
  
  const cancelSubscriptionMutation = useMutation(CancelSubscription, {
    onSuccess: () => {
      queryClient.invalidateQueries(["Customer", user.accountId]);
      setResultMessage('Subscription cancelled successfully!');
      setShowResult(true);
      setIsLoading(false);
    },
    onError: (error) => {
      setResultMessage('Failed to cancel subscription: ' + (error.message || 'Unknown error'));
      setShowResult(true);
      setIsLoading(false);
    }
  });
  
  const customerPortalMutation = useMutation(CreateCustomerPortalSession, {
    onSuccess: (response) => {
      window.location.href = response.data.redirect_url;
    }
  });
  
  const handleMenuClick = (event, type) => {
    setAnchorEl(event.currentTarget);
    setMenuType(type);
  };
  
  const handleMenuClose = () => {
    setAnchorEl(null);
    setMenuType('');
  };
  
  const handleCardMenuItemClick = (cardId, action) => {
    setSelectedCardId(cardId);
    setDialogType(action);
    setConfirmDialogOpen(true);
    handleMenuClose();
  };
  
  const handleDialogOpen = (type) => {
    setDialogType(type);
    setDialogOpen(true);
    setShowResult(false);
    setResultMessage('');
  };
  
  const handleDialogClose = () => {
    setDialogOpen(false);
    setConfirmDialogOpen(false);
    setDialogType('');
    setSelectedValue('');
    setSelectedCardId('');
    setShowResult(false);
    setResultMessage('');
    setIsLoading(false);
  };
  
  const handleConfirmCardAction = async () => {
    setConfirmDialogOpen(false);
    setIsLoading(true);
    
    if (dialogType === 'removeCard') {
      removeCardMutation.mutate({ cardId: selectedCardId });
    } else if (dialogType === 'defaultCard') {
      setDefaultCardMutation.mutate({ cardId: selectedCardId });
    }
  };
  
  const handleCancelSubscription = async () => {
    if (!selectedValue) return;
    
    setIsLoading(true);
    cancelSubscriptionMutation.mutate({ subscriptionId: selectedValue });
  };
  
  const handleCustomerPortal = () => {
    customerPortalMutation.mutate();
  };
  
  const handleClearAndLogout = async () => {
    await Clear();
    await Logout();
    await refetch();
    window.location.href = "/auth/login";
  };
  
  const actionItems = [
    { icon: <RemoveCardIcon />, text: 'Remove Payment Method', action: 'cardMenu', type: 'removeCard' },
    { icon: <DefaultCardIcon />, text: 'Set Default Payment Method', action: 'cardMenu', type: 'defaultCard' },
    { icon: <CancelIcon />, text: 'Cancel Subscription', action: 'dialog', type: 'cancelSubscription' },
    { icon: <PortalIcon />, text: 'Open Customer Portal', action: 'direct', type: 'portal' },
    { icon: <ClearIcon />, text: 'Clear Cache', action: 'direct', type: 'clear' },
    { icon: <LogoutIcon />, text: 'Logout', action: 'direct', type: 'logout' }
  ];
  
  const handleItemClick = (item, e) => {
    if (item.action === 'direct') {
      switch (item.type) {
        case 'portal':
          handleCustomerPortal();
          break;
        case 'clear':
          Clear();
          break;
        case 'logout':
          handleClearAndLogout();
          break;
        default:
          break;
      }
    } else if (item.action === 'cardMenu') {
      handleMenuClick(e, item.type);
    } else if (item.action === 'dialog') {
      handleDialogOpen(item.type);
    }
  };
  
  const renderDialogContent = () => {
    if (showResult) {
      return (
        <Alert severity={resultMessage.includes('successfully') ? 'success' : 'error'}>
          {resultMessage}
        </Alert>
      );
    }
    
    if (isLoading) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <CircularProgress size={24} />
          <Typography>Processing...</Typography>
        </div>
      );
    }
    
    switch (dialogType) {
      case 'cancelSubscription':
        return (
          <FormControl fullWidth margin="normal">
            <InputLabel>Select Subscription</InputLabel>
            <Select
              value={selectedValue}
              onChange={(e) => setSelectedValue(e.target.value)}
              label="Select Subscription"
            >
              {customerData?.data?.subscriptions?.data?.map((subscription) => (
                <MenuItem key={subscription.id} value={subscription.id}>
                  {subscription.plan?.name || 'Current Subscription'} - ${(subscription.plan?.amount / 100).toFixed(2)}
                </MenuItem>
              )) || []}
            </Select>
          </FormControl>
        );
      default:
        return null;
    }
  };
  
  const getDialogTitle = () => {
    switch (dialogType) {
      case 'removeCard':
        return 'Remove Payment Method';
      case 'defaultCard':
        return 'Set Default Payment Method';
      case 'cancelSubscription':
        return 'Cancel Subscription';
      default:
        return 'Confirm Action';
    }
  };
  
  const getDialogActions = () => {
    if (showResult) {
      return <Button onClick={handleDialogClose}>Close</Button>;
    }
    
    if (dialogType === 'cancelSubscription') {
      return (
        <>
          <Button onClick={handleDialogClose}>Cancel</Button>
          <Button 
            onClick={handleCancelSubscription} 
            variant="contained"
            disabled={!selectedValue || isLoading}
            color="error"
          >
            Cancel Subscription
          </Button>
        </>
      );
    }
    
    return <Button onClick={handleDialogClose}>Close</Button>;
  };
  
  return (
    <Paper 
      variant="outlined"
      sx={{
        borderRadius: borderRadius,
        border: `${border}px solid`,
        borderColor: borderColor
      }}
    >
      <Typography variant="h6" sx={{ p: 2, pb: 1 }}>
        Dashboard Actions
      </Typography>
      <List dense>
        {actionItems.map((item, index) => (
          <ListItem 
            key={index}
            button
            onClick={(e) => handleItemClick(item, e)}
          >
            <ListItemIcon>
              {item.icon}
            </ListItemIcon>
            <ListItemText primary={item.text} />
          </ListItem>
        ))}
      </List>
      
      {/* Card Actions Menu */}
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        {(menuType === 'removeCard' || menuType === 'defaultCard') && 
          cardsData?.data?.map((card) => (
            <MenuItem 
              key={card.id} 
              onClick={() => handleCardMenuItemClick(card.id, menuType)}
            >
              {card.brand} **** **** **** {card.last4}
              {card.default_source && ' (Current Default)'}
            </MenuItem>
          ))
        }
      </Menu>
      
      {/* Card Action Confirmation Dialog */}
      <Dialog open={confirmDialogOpen} onClose={handleDialogClose}>
        <DialogTitle>{getDialogTitle()}</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to {dialogType === 'removeCard' ? 'remove' : 'set as default'} this payment method?
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleDialogClose}>Cancel</Button>
          <Button 
            onClick={handleConfirmCardAction} 
            variant="contained"
            color={dialogType === 'removeCard' ? 'error' : 'primary'}
          >
            Confirm
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Other Actions Dialog */}
      <Dialog open={dialogOpen} onClose={handleDialogClose} maxWidth="sm" fullWidth>
        <DialogTitle>{getDialogTitle()}</DialogTitle>
        <DialogContent>
          {renderDialogContent()}
        </DialogContent>
        <DialogActions>
          {getDialogActions()}
        </DialogActions>
      </Dialog>
    </Paper>
  );
};

export default QuickActionsPanel;